package com.adinnet.api.sentence.service.impl;

import com.adinnet.api.childMaxStudy.mapper.ChildMaxStudyMapper;
import com.adinnet.api.childMaxStudy.model.ChildMaxStudy;
import com.adinnet.api.childStudyRecord.mapper.ChildStudyRecordMapper;
import com.adinnet.api.childStudyRecord.model.ChildStudyRecord;
import com.adinnet.api.sentence.model.Sentence;
import com.adinnet.api.sentence.mapper.SentenceMapper;
import com.adinnet.api.sentence.service.SentenceService;
import com.adinnet.core.JsonResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 跟随训练表（短句） 服务实现类
 * </p>
 *
 * @author zYshuai
 * @since 2020-12-02
 */
@Service
public class SentenceServiceImpl extends ServiceImpl<SentenceMapper, Sentence> implements SentenceService {

    @Autowired
    private SentenceMapper sentenceMapper;

    @Autowired
    private ChildMaxStudyMapper childMaxStudyMapper;

    @Autowired
    private ChildStudyRecordMapper childStudyRecordMapper;

    /**
     * 根据短句id查询儿童单个短句信息
     * 1，查询最高分，2，查最新学习记录
     * @param childId
     * @param sentenceId
     * @return
     */
    @Override
    public JsonResult sentenceDetails(Integer childId, Integer sentenceId) {
        Sentence sentence = sentenceMapper.selectById(sentenceId);
        //历史高分和历史录音(最新一条)
        QueryWrapper<ChildMaxStudy> childWrapper = new QueryWrapper<>();
        childWrapper.eq("child_id",childId).eq("type", 4).eq("third_id", sentenceId).eq("deleted", 0);
        ChildMaxStudy childMaxStudy = childMaxStudyMapper.selectOne(childWrapper);
        if (null == childMaxStudy) {
            sentence.setHistoryScore(0);
        } else {
            sentence.setHistoryScore(childMaxStudy.getPeaseNum());
        }
        QueryWrapper<ChildStudyRecord> studyWrapper = new QueryWrapper<>();
        studyWrapper.eq("child_id",childId).eq("type", 4).eq("third_id", sentence.getId()).eq("deleted", 0).orderByDesc("created_date").last("limit 1");
        List<ChildStudyRecord> studyRecords = childStudyRecordMapper.selectList(studyWrapper);
        if (CollectionUtils.isEmpty(studyRecords)) {
            sentence.setHistoryReadErrorWords("");
            sentence.setHistoryReadUrl("");
        } else {
            sentence.setHistoryReadUrl(studyRecords.get(0).getReadUrl()==null?"":studyRecords.get(0).getReadUrl());
            sentence.setHistoryReadErrorWords(studyRecords.get(0).getErrorWords()==null?"":studyRecords.get(0).getErrorWords());
        }
        return JsonResult.ok().put("data", sentence);
    }
}
